package com.guozcc.gateway.autofilter.base;

import lombok.extern.slf4j.Slf4j;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.rewrite.ModifyResponseBodyGatewayFilterFactory;
import org.springframework.cloud.gateway.filter.factory.rewrite.RewriteFunction;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Slf4j
public abstract class AbstractGatewayResponseBaseFilter implements GatewayFilter, RewriteFunction<byte[], String>, HandlerResponseBody {

    private GatewayFilter responseFilter;

    public AbstractGatewayResponseBaseFilter(ModifyResponseBodyGatewayFilterFactory modifyResponseBody){

        this.responseFilter=modifyResponseBody.apply(new ModifyResponseBodyGatewayFilterFactory.Config()
                .setRewriteFunction(byte[].class, String.class, this));

    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        return responseFilter.filter(exchange, chain);
    }

    abstract public String handlerResBody(ServerWebExchange serverWebExchange, byte[] bytes);

    @Override
    public Publisher<String> apply(ServerWebExchange serverWebExchange, byte[] responseBytes) {

        String responseBody = handlerResBody(serverWebExchange,responseBytes);
        return Mono.just(responseBody);
    }
}
